package com.example.download;

import android.util.Log;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;

public abstract class HttpDownloader {


    /**
     * 根据URL下载文件，前提是这个文件当中的内容是文本，函数的返回值就是文件当中的内容
     * 1.创建一个URL对象
     * 2.通过URL对象，创建一个HttpURLConnection对象
     * 3.得到InputStram
     * 4.从InputStream当中读取数据
     *
     * @param urlStr
     *
     * @return
     */
    public String download(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            // 创建一个URL对象
            URL url = new URL(urlStr);
            // 创建一个Http连接
            HttpURLConnection urlConn = (HttpURLConnection) url
                    .openConnection();
            System.out.println(urlConn);
            InputStream reader = urlConn.getInputStream();

            // 使用IO流读取数据
            buffer = new BufferedReader(new InputStreamReader(urlConn
                    .getInputStream()));
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.printf(sb.toString());
        return sb.toString();
    }


    /**
     * 下载二进制文件
     *
     * @param urlString
     *
     * @return
     */
    public byte[] downLoad(String urlString) {

        int increment = 1024 * 500;

        byte[] buffer = new byte[0];

        HttpURLConnection conn = null;
        URL url = null;

        try {
            url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            // 设置连接超时
            conn.setConnectTimeout(6 * 1000);

            // 对响应码进行判断:
            if (conn.getResponseCode() != 200){
//                throw new RuntimeException("请求url失败");
                Log.i("INFO", "请求url[" + url +"]失败");
                return buffer;
            }

            buffer = new byte[increment];
            InputStream is = conn.getInputStream();

            byte[] temp = new byte[10240];

            int l = 0;
            int bufferPos = 0;
            while ((l = is.read(temp, 0, temp.length)) != -1) {
                // 如果下一步长度将要超出范围则另起一个数组
                if (bufferPos + l > buffer.length) {

                    byte[] oldBuffer = buffer;

                    buffer = new byte[oldBuffer.length + increment];

                    System.arraycopy(oldBuffer, 0, buffer, 0, bufferPos);
                    oldBuffer = null;
                }
                System.arraycopy(temp, 0, buffer, bufferPos, l);
                bufferPos += l;
            }

            temp = null;

            /**
             * 真实结果
             */
            byte[] oldBuffer = buffer;
            buffer = new byte[bufferPos];
            System.arraycopy(oldBuffer, 0, buffer, 0, bufferPos);
            oldBuffer = null;


        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("INFO", "畸型的Url....");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (null != conn) {
                conn.disconnect();
            }
        }

        System.out.println("下载文件大小：" + buffer.length / 1024 + "k");
        return buffer;
    }


}
